﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyApplication.Models;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace MyApplication.Controllers
{
    public class UploaderController : Controller
    {
        private static String UpLoadPathBase="/Resources";
        private static String[] ImageTypes = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
        private static String[] FileTypes = { ".rar", ".doc", ".docx", "ppt", "xls", ".zip", ".pdf", ".txt", ".swf", ".wmv" };

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
        public JsonResult ImageUp(FormCollection Form)
        {
            String State = String.Empty;
            if (Request.Files.Count > 0)
            {
                var RequestFile = Request.Files[0];
                var RelativePath = "/Image/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                var NewFileName = Guid.NewGuid() +Path.GetExtension(RequestFile.FileName);
                State = this.SaveFile(RequestFile, RelativePath, NewFileName, UploadType.Image);
                if (State == "SUCCESS")
                {

                    return Json(new FileInfoModel
                    {
                        state = State,
                        title = Form["pictitle"],
                        url = RelativePath+NewFileName,
                        original = Form["fileName"].Split(',')[1]
                    }, "text/plain");
                }
            }
            return Json(new FileInfoModel
            {
                state = State,
                url = ""
            }, "text/plain");
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
        public JsonResult FileUp(FormCollection Form)
        {
            String State = String.Empty;
            if (Request.Files.Count > 0)
            {
                var RequestFile = Request.Files[0];
                var FileExt =Path.GetExtension(RequestFile.FileName);
                var RelativePath = "/Attachment/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                var NewFileName = Guid.NewGuid() + FileExt;
                State = this.SaveFile(RequestFile, RelativePath,NewFileName, UploadType.File);
                if (State == "SUCCESS")
                {
                    return Json(new FileInfoModel
                    {
                        state = State,
                        url = RelativePath + NewFileName,
                        fileType = FileExt,
                        original = RequestFile.FileName
                    }, "text/plain");
                }
            }
            return Json(new FileInfoModel
            { 
              state=State,
              url=String.Empty
            });
        }

        /// <summary>
        /// 图片管理
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
        public JsonResult ImageManager(FormCollection Form)
        {
            string path = Server.MapPath(UpLoadPathBase + "/Image/"); //最好使用缩略图地址，否则当网速慢时可能会造成严重的延时

            #region 返回拼接的字符串
            /*
            if (Form["action"] == "get")
            {
                String str = String.Empty;
                DirectoryInfo info = new DirectoryInfo(path);

                //目录验证
                if (info.Exists)
                {
                    DirectoryInfo[] infoArr = info.GetDirectories();
                    foreach (DirectoryInfo tmpInfo in infoArr)
                    {
                        foreach (FileInfo fi in tmpInfo.GetFiles())
                        {
                            if (Array.IndexOf(ImageTypes, fi.Extension) != -1)
                            {
                                str += "/Image/" + tmpInfo.Name + "/" + fi.Name + "ue_separate_ue";
                            }
                        }
                    }
                }
                return Content(str, "text/plain");
            }
            return Content(String.Empty, "text/plain");
            */
            #endregion

            #region 返回Json对象
            if (Form["action"] == "get")
            {
                IList<Object> Objs = new List<Object>();
                DirectoryInfo Info = new DirectoryInfo(path);

                //目录验证
                if (Info.Exists)
                {
                    DirectoryInfo[] Directories = Info.GetDirectories();
                    foreach (DirectoryInfo d in Directories)
                    {
                        foreach (FileInfo f in d.GetFiles())
                        {
                            if (Array.IndexOf(ImageTypes, f.Extension) != -1)
                            {
                                if (!System.IO.File.Exists(d + "Thumbnail" + f.FullName))
                                {
                                    this.SaveThumbnail("/Image/" + d.Name + "/" + f.Name, "/Image/" + d.Name + "/Thumbnail/" + f.Name, 100, 100);
                                }
                                Objs.Add(new {
                                    data_ue_src = "/Image/" + d.Name + "/" + f.Name,
                                    src = "/Image/" + d.Name + "/Thumbnail/" + f.Name
                                });
                            }
                        }
                    }
                }
                return Json(Objs, "text/plain");
            }
            return Json(String.Empty, "text/plain");
            #endregion
        }

        /// <summary>
        /// 上传涂鸦
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
        public ActionResult ScrawlUp(FormCollection Form)
        {
            String State = String.Empty;

            if (Form["action"] == "tmpImg")
            {
                if (Request.Files.Count > 0)
                {
                    var RequestFile = Request.Files[0];
                    var RelativePath = "/Temp/";
                    var NewFileName = Guid.NewGuid() + Path.GetExtension(RequestFile.FileName);
                    State = this.SaveFile(RequestFile, RelativePath, NewFileName, UploadType.Image);

                    return JavaScript(String.Format("<script type=\"text/javascript\">parent.ue_callback('{0}','{1}')</script>",
                        State=="SUCCESS"?(RelativePath + NewFileName):"", State));
                }
            }
            else
            {
                var RelativePath = "/Scrawl/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                var FileName = Guid.NewGuid() + ".png";
                State = this.UpScrawl(RelativePath, FileName, Form["content"]);

                Json(new FileInfoModel
                {
                    url =(State=="SUCCESS")?RelativePath+FileName:"",
                    state = State,
                });
            }

            return Json(true);
        }

        /// <summary>
        /// 下载远程图片
        /// </summary>
        /// <returns></returns>
        public JsonResult GetRemoteImage(FormCollection Form)
        {
            var RelativePath = "/Image/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var SavePath = Server.MapPath(UpLoadPathBase + RelativePath);       //保存文件地址

            string Uri = Server.HtmlEncode(Form["upfile"]).Replace("&amp;", "&");
            string[] ImgUrls = Regex.Split(Uri, "ue_separate_ue", RegexOptions.IgnoreCase);

            IList<String> tmpNames = new List<String>();
            String FileName = String.Empty;
            String currentType = String.Empty;
            try
            {
                using (WebClient Client = new WebClient())
                {
                    foreach (var Url in ImgUrls)
                    {
                        if (Url.Substring(0, 7) != "http://")
                        {
                            tmpNames.Add("error!");
                            continue;
                        }

                        //格式验证
                        currentType = Url.Substring(Url.LastIndexOf('.')).ToLower();
                        if (Array.IndexOf(ImageTypes, currentType) == -1)
                        {
                            tmpNames.Add("error!");
                            continue;
                        }

                        using (HttpWebResponse Resp = (HttpWebResponse)WebRequest.Create(Url).GetResponse())
                        {
                            //http检测
                            if (Resp.ResponseUri.Scheme.ToLower().Trim() != "http")
                            {
                                tmpNames.Add("error!");
                                continue;
                            }
                            //大小验证
                            if (Resp.ContentLength > 2000 * 1024)
                            {
                                tmpNames.Add("error!");
                                continue;
                            }
                            //死链验证
                            if (Resp.StatusCode != HttpStatusCode.OK)
                            {
                                tmpNames.Add("error!");
                                continue;
                            }
                            //检查mime类型
                            if (Resp.ContentType.IndexOf("image") == -1)
                            {
                                tmpNames.Add("error!");
                                continue;
                            }
                        }

                        //创建保存位置
                        if (!Directory.Exists(SavePath))
                        {
                            Directory.CreateDirectory(SavePath);
                        }

                        //写入文件
                        FileName = Guid.NewGuid() + currentType;
                        Client.DownloadFile(Url, SavePath + FileName);
                        tmpNames.Add(RelativePath + FileName);

                    }
                }
            }
            catch (Exception)
            {
                tmpNames.Add("error!");
            }
            return Json(new
            {
                url = tmpNames.Aggregate((m, n) => m + "ue_separate_ue" + n),
                tip = "远程图片抓取成功！",
                srcUrl = Uri
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ContentResult GetMovie(FormCollection Form)
        {
            string key = Server.HtmlEncode(Form["searchKey"]);
            string type = Server.HtmlEncode(Form["videoType"]);

            Uri httpURL = new Uri("http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw=" + key + "&pageNo=1&pageSize=20&channelId=" + type + "&inDays=7&media=v&sort=s");
            using (WebClient MyWebClient = new WebClient())
            {
                MyWebClient.Credentials = CredentialCache.DefaultCredentials;           //获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                Byte[] pageData = MyWebClient.DownloadData(httpURL);
                return Content(Encoding.UTF8.GetString(pageData));
            }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="PostedFile"></param>
        /// <param name="Path"></param>
        /// <param name="FileName"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        private String SaveFile(HttpPostedFileBase PostedFile,String Path, String FileName, UploadType Type)
        {
            try
            {
                String SavePath = Server.MapPath(UpLoadPathBase + Path);
                String FileExt = FileName.Substring(FileName.LastIndexOf('.'));

                if (Type == UploadType.Image)
                {
                    if (!ImageTypes.Contains(FileExt))
                    {
                        return "不允许的文件类型";
                    }
                    if (PostedFile.ContentLength > 2 * 1024 * 1024)
                    {
                        return "文件大小超出网站限制";
                    }
                }
                else
                {
                    if (!FileTypes.Contains(FileExt))
                    {
                        return "不允许的文件类型";
                    }
                    if (PostedFile.ContentLength > 20 * 1024 * 1024)
                    {
                        return "文件大小超出网站限制";
                    }
                }
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
                PostedFile.SaveAs(SavePath+FileName);
            }
            catch(Exception)
            {
                return "保存文件异常";
            }
            return "SUCCESS";
        }

        /// <summary>
        /// 保存涂鸦文件
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="FileName"></param>
        /// <param name="Base64Data"></param>
        /// <returns></returns>
        private String UpScrawl(String Path, String FileName, String Base64Data)
        {
            String SavePath = Server.MapPath(UpLoadPathBase + Path);
            FileStream Fs = null;
            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
                //生成图片
                Fs = System.IO.File.Create(SavePath + FileName);
                byte[] Bytes = Convert.FromBase64String(Base64Data);
                Fs.Write(Bytes, 0, Bytes.Length);

                return "SUCCESS";
            }
            catch (Exception)
            {
                return "未知错误";
            }
            finally
            {
                Fs.Close();
            }
        }

        private void SaveThumbnail(string originalFile, string newFile, int maxHeight, int maxWidth)
        {
            originalFile = Server.MapPath(UpLoadPathBase + originalFile);
            newFile = Server.MapPath(UpLoadPathBase + newFile);
            using (Image originalImg = Image.FromFile(originalFile))
            {
                ImageFormat thisFormat = originalImg.RawFormat;
                int newWidth, newHeight;
                // scale down the smaller dimension
                if (maxWidth * originalImg.Height < maxHeight * originalImg.Width)
                {
                    newWidth = maxWidth;
                    newHeight = (int)Math.Round((decimal)originalImg.Height * maxWidth / originalImg.Width);
                }
                else
                {
                    newHeight = maxHeight;
                    newWidth = (int)Math.Round((decimal)originalImg.Width * maxHeight / originalImg.Height);
                }
                Bitmap outBmp = new Bitmap(newWidth, newHeight);
                using (Graphics g = Graphics.FromImage(outBmp))
                {
                    // 设置画布的描绘质量
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(originalImg, new Rectangle(0, 0, newWidth, newHeight),
                    0, 0, originalImg.Width, originalImg.Height, GraphicsUnit.Pixel);
                }
                // 以下代码为保存图片时,设置压缩质量
                EncoderParameters encoderParams = new EncoderParameters();
                encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, new long[] { 100 });
                //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICI = arrayICI.Where(m => m.FormatDescription.Equals("JPEG")).SingleOrDefault();
                if (jpegICI != null)
                {
                    outBmp.Save(newFile, jpegICI, encoderParams);
                }
                else
                {
                    outBmp.Save(newFile, thisFormat);
                }
                outBmp.Dispose();
            }
        } 
    }

    public enum UploadType
    {
        Image=0,
        File=1
    }
}
